package com.ysq.www.api.user.controller;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysq.www.api.user.entity.User;
import com.ysq.www.api.user.entity.UserEntry;
import com.ysq.www.api.user.entity.WxConfig;
import com.ysq.www.api.user.service.IUserService;
import com.ysq.www.api.user.service.IWxConfigService;
import com.ysq.www.common.annotation.AuthToken;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.code.RandomValidateCodeUtil;
import com.ysq.www.common.utils.message.HttpClientUtils;
import com.ysq.www.common.utils.message.SendMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 测试用户表
 前端控制器
 * </p>
 *
 * @author dql
 * @since 2020-08-05
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IWxConfigService wxConfigService;

    @PostMapping("/selectById")
    @AuthToken
    public ResultMsg selectById(Integer userId){
        User user = userService.getById(userId);
        return ResultMsg.SUCCESS.setNewMsg("查询成功").setNewData(user);
    }

    /**
     * 微信小程序用户授权登录
     * @param code
     * @return
     */
    @PostMapping("/wxLogin")
    @AuthToken
    public ResultMsg add(@RequestParam("code") String code,
                         @RequestParam("nickname") String nickname,
                         @RequestParam("headUrl") String headUrl){
        if (StringUtils.isEmpty(code)) return ResultMsg.INSERT_ERROR.setNewMsg("参数为空，新增失败!");
        try {
            JSONObject js = getOpenIdByCode(code);
            String openId = js.getString("openid");
            if (StringUtils.isEmpty(openId)){
                int errCode = js.getIntValue("errcode");
                log.info("微信授权失败错误码："+errCode);
                return ResultMsg.WX_AUTHOR_ERROR.setNewData("微信授权失败错误码："+errCode);
            }
            QueryWrapper<User> wrapper = new QueryWrapper();
            wrapper.eq("openId",openId).eq("status",0);
            User user = userService.getOne(wrapper);
            //用户存在直接返回用户信息
            if (user != null) return ResultMsg.WX_AUTHOR_SUCCESS.setNewData(user);
            //用户不存在，创建新用户
            user.setNickName(nickname);
            user.setOpenId(openId);
            user.setHeadUrl(headUrl);
            user.setCreateTime(new Date());
            boolean save = userService.save(user);
            if (!save){
                return ResultMsg.INSERT_ERROR.setNewMsg("新增用户失败，内部错误");
            }
            return ResultMsg.WX_AUTHOR_SUCCESS.setNewData(user);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.WX_AUTHOR_ERROR.setNewMsg("微信授权内部错误");
        }
    }


    /**
     * 解密手机号
     * @param code 微信授权码
     * @param data
     * @param iv
     * @return
     */
    @GetMapping("/getPhone")
    @AuthToken
    public ResultMsg getPhone(String code,String data,String iv){
        if (StringUtils.isEmpty(code)) return ResultMsg.WX_AUTHOR_ERROR;
        WxConfig wc = wxConfigService.getById(1);
        try {
            JSONObject js = this.getOpenIdByCode(code);
            if (js.isEmpty()) return ResultMsg.WX_AUTHOR_ERROR.setNewMsg("授权失败,内部错误!");
            String openId = js.getString("openid");
            if (StringUtils.isEmpty(openId)){
                int errCode = js.getIntValue("errcode");
                log.info("微信授权失败错误码："+errCode);
                return ResultMsg.WX_AUTHOR_ERROR.setNewData("微信授权失败错误码："+errCode);
            }
            String session_key = js.getString("session_key");//会话秘钥
            //解密信息获取手机号
            String decrypt  = SendMessageUtil.decrypt(data, session_key, iv, "UTF-8");
            if (StringUtils.isEmpty(decrypt)) return ResultMsg.WX_AUTHOR_ERROR.setNewMsg("解密手机号失败!");
            return ResultMsg.WX_AUTHOR_SUCCESS.setNewMsg("解密手机号成功!").setNewData(decrypt);
        }catch (Exception e){
            e.printStackTrace();
            return ResultMsg.WX_AUTHOR_ERROR.setNewMsg("授权失败，程序异常!");
        }
    }


    /**
     * 我的名片查询
     * @param userId
     * @return
     */
    @GetMapping("/selectCard")
    @AuthToken
    public ResultMsg selectCardById(Integer userId){
        User user = userService.selectCardById(userId);
        return ResultMsg.SUCCESS.setNewMsg("查询成功").setNewData(user);
    }


    /**
     * 授权登录获取登录信息
     * @param code 微信登录凭证code
     * @return
     */
    public JSONObject getOpenIdByCode(String code){
        WxConfig wc = wxConfigService.getById(1);
        JSONObject js = null;
        try {
            js = HttpClientUtils.getWxUserOpenid(code, wc.getAppId(), wc.getAppSecret());
            String openId = js.getString("openid");
            if (StringUtils.isEmpty(openId)){
                int errCode = js.getIntValue("errcode");
                log.info("微信授权失败错误码："+errCode);
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return js;
    }


    /**
     * 生成验证码
     */
    @GetMapping("/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response){
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查验验证码
     */
    @GetMapping("/checkVerify")
    public ResultMsg checkVerify(String code, HttpSession session){
        //从session中获取随机数
        //String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
        //不区分大小
        String random = String.valueOf(session.getAttribute("RANDOMVALIDATECODEKEY")).toLowerCase();
        if (random == null) return ResultMsg.LOGIN_ERROR.setNewMsg("验证码已过期");
        if (!random.equals(code)) return ResultMsg.LOGIN_ERROR.setNewMsg("验证码错误");

        return ResultMsg.SUCCESS.setNewMsg("验证通过");
    }

}
